package bsserver.response;

import bsserver.Main;
import bsserver.Request;
import bsserver.RequestURI;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Response class for handling HEAD Requests
 * @author tblackstone
 */
public class HEADResponse extends Response {

    /**
     * Creates a new Response to a HEAD request
     * @param r the HEAD Request which caused this Response to be generated
     */
    public HEADResponse(Request r) {
        super(r);
    }

    /**
     * Process a HEAD Request to determine how to respond to it
     * @param r the Request to process
     * @return an appropriate Response object
     */
    public static Response process(Request r) {

        Response response;

        // Check Resource Permissions
        String validUser = findClientPermissions(r);

        if(!r.getAuthInfo().isReadable()) {
            return new ErrorResponse(r, 404);
        }

        if (validUser == null) {
            Response authRequiredResponse = new ErrorResponse(r, 401);
            authRequiredResponse.setHeader("WWW-Authenticate",
                    "Basic realm=\"" + r.getAuthInfo().getAuthName() + "\"");
            return authRequiredResponse;
        }
        r.setRemoteUser(validUser);

        RequestURI requestURI = r.getRequestURI();

        if (!requestURI.resourceExists()) {
            return new ErrorResponse(r, 404);

        } else if (requestURI.isScript()) {
            // Script execution not allowed with HEAD
            return new ErrorResponse(r, 405);

        } else {

            response = new HEADResponse(r);
            response.setDefaultHeaders();

            // Resource is a file
            File resource = new File(requestURI.getAbsolutePath());

            long length = resource.length();
            response.setHeader("Content-Length", Long.toString(length));

            // Set Last-Modifed Header
            long modifiedDate = resource.lastModified();
            SimpleDateFormat f = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
            f.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = f.format(new Date(modifiedDate));
            response.setHeader("Last-Modified", date);

            // Set Content-type header
            String contentType = Main.HttpdConfig.get("DefaultType");
            if (contentType == null) {
                contentType = "text/plain";
            }
            int extensionPos = resource.getName().lastIndexOf(".");
            if (extensionPos != -1) {
                String extension = resource.getName().substring(extensionPos + 1);
                String newType = Main.MimeType.getType(extension);
                if (newType != null) {
                    contentType = newType;
                }
            }

            response.setHeader("Content-Type", contentType);

            response.setStatus(200);

            return response;
        }

    }
}
